<template>
    <!-- <h1>药品列表</h1> -->
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="药品列表" name="first">
            <div style="display: flex; margin-top: 20px">
                <el-input
                    v-model="input"
                    style="width: 240px"
                    placeholder="输入名称"
                />
                <div class="mb-4" style="margin-left: 20px">
                    <el-button type="primary" @click="search">搜索</el-button>
                </div>
            </div>
            <el-table :data="tableData" stripe style="width: 100%">
                <el-table-column prop="drId" label="编号" width="180" />
                <el-table-column prop="drName" label="名称" width="180" />
                <el-table-column prop="drPrice" label="价格">
                    <template v-slot="{ row }"> {{ row.drPrice }} 元 </template>
                </el-table-column>
                <el-table-column label="图片">
                    <template v-slot="{ row }">
                        <span v-if="!row.imgUrl">暂无图片</span>
                        <div class="demo-image__preview">
                            <el-image
                                style="width: 100px; height: 100px"
                                :src="'/src/assets/' + row.imgUrl"
                                :zoom-rate="1.2"
                                :max-scale="7"
                                :min-scale="0.2"
                                :initial-index="4"
                                fit="cover"
                            />
                        </div>
                    </template>
                </el-table-column>
                <!-- <el-table-column prop="drNumber" label="库存" /> -->
                <el-table-column width="180" label="操作">
                    <template v-slot="{ row }">
                        <el-button type="primary" @click="addToCart(row.drId)"
                            >加入购物车</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
            <el-dialog
                :visible="dialogVisible"
                @update:visible="dialogVisible = $event"
                width="50%"
            >
                <img
                    :src="'/src/assets/' + imageUrl"
                    style="max-width: 100%; max-height: 100%"
                />
            </el-dialog>
        </el-tab-pane>

        <el-tab-pane label="购物车" name="third">
            <el-table :data="cartData" stripe style="width: 100%">
                <el-table-column prop="drId" label="编号" width="180" />
                <el-table-column prop="drName" label="名称" width="180" />
                <el-table-column prop="drPrice" label="单价">
                    <template v-slot="{ row }"> {{ row.drPrice }} 元 </template>
                </el-table-column>
                <el-table-column label="数量" width="180">
                    <template v-slot="{ row }">
                        <div class="quantity-control">
                            <el-button
                                type="primary"
                                @click="reduceToCart(row.drId)"
                                >减</el-button
                            >
                            {{ row.quantity }}
                            <el-button
                                type="primary"
                                @click="addToCart(row.drId)"
                                >加</el-button
                            >
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <div class="mb-4" style="margin-left: 20px">
                <p>总价: {{ totalPrice }}</p>
            </div>
            <div class="mb-4" style="margin-left: 20px">
                <el-button type="primary" @click="pay">结算</el-button>
            </div>
            <div class="mb-4" style="margin-left: 20px">
                <p>账户余额: {{ account }}</p>
            </div>
            <div class="mb-4" style="margin-left: 20px">
                <p>结算后剩余: {{ leaveAccount }}</p>
            </div>
        </el-tab-pane>
        <el-tab-pane label="订单" name="fourth">
            <el-table :data="orderList" stripe style="width: 100%">
                <el-table-column prop="id" label="订单编号" width="180" />
                <el-table-column prop="record" label="订单详情" />
                <el-table-column prop="totalPrice" label="订单价格" />
                <el-table-column width="180" label="操作">
                    <template v-slot="{ row }">
                        <el-button
                            type="primary"
                            :disabled="row.status === 1"
                            @click="refund(row.id)"
                            >退单</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
        </el-tab-pane>
    </el-tabs>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import type { TabsPaneContext } from 'element-plus'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { el } from 'element-plus/es/locale'

const activeName = ref('first')
const tableData = ref([])
const cartData = ref([])
const orderList = ref([])
let dialogVisible = true
let imageUrl = 'upload/1.jpg'

const handleClick = (tab: TabsPaneContext, event: Event) => {
    console.log(tab, event)
}
const input = ref('')

const addToCart = (id: any) => {
    axios
        .post('/api/drug/add-to-cart', { drId: id })
        .then((response) => {
            fetchCartData()
            open1()
        })
        .catch((error) => {
            open2()
        })
}
const reduceToCart = (id: any) => {
    axios
        .post('/api/drug/reduce-to-cart', { drId: id })
        .then((response) => {
            fetchCartData()
            open1()
        })
        .catch((error) => {
            open2()
        })
}
const search = () => {
    axios
        .get('/api/drug', {
            params: {
                drName: input.value
            }
        })
        .then((response) => {
            tableData.value = response.data
        })
        .catch((error) => {
            console.error('Error fetching data:', error)
        })
}
const fetchCartData = () => {
    axios
        .get('/api/cart')
        .then((response) => {
            cartData.value = response.data
        })
        .catch((error) => {
            console.error('Error fetching cart data:', error)
        })
}
const fetchOrderList = () => {
    axios
        .get('/api/drug/order')
        .then((response) => {
            orderList.value = response.data
        })
        .catch((error) => {
            console.error('Error fetching order list:', error)
        })
}
const pay = () => {
    const chars = '0123456789'
    let orderId = ''
    for (let i = 0; i < 8; i++) {
        const randomIndex = Math.floor(Math.random() * chars.length)
        orderId += chars[randomIndex]
    }
    const orderDetails = cartData.value
        .map((item) => `${item.drName} * ${item.quantity}`)
        .join('\n')
    console.log(orderDetails)
    if (account - totalPrice.value >= 0) {
        axios
            .post('/api/drug/pay', {
                id: orderId,
                record: orderDetails,
                totalPrice: totalPrice.value
            })
            .then((response) => {
                fetchCartData()
                open1()
            })
            .catch((error) => {
                open2()
            })
    } else {
        ElMessage.error('金额不足，无法结算')
    }
}
const refund = (id: any) => {
    axios
        .put('/api/drug/refund', { id: id })
        .then((response) => {
            fetchOrderList()
            open1()
        })
        .catch((error) => {
            open2()
        })
}

const showLargeImage = (imageUrl) => {
    alert('####')
    imageUrl = imageUrl
    // 显示弹窗
    dialogVisible = true
}

onMounted(() => {
    search()
    fetchCartData()
    fetchOrderList()
})
const totalPrice = computed(() => {
    return cartData.value.reduce(
        (total, item) => total + item.drPrice * item.quantity,
        0
    )
})

const account = 190
let leaveAccount = computed(() => {
    return account - totalPrice.value >= 0
        ? account - totalPrice.value
        : '余额不足够支付'
})
const open1 = () => {
    ElMessage({
        message: '操作成功',
        type: 'success'
    })
}
const open2 = () => {
    ElMessage.error('操作失败')
}
</script>

<style>
.demo-tabs {
    position: relative;
}
.demo-tabs > .el-tabs__content {
    position: absolute;
    top: 0;
    left: 0;
    padding: 32px;
    color: #6b778c;
    font-size: 32px;
    font-weight: 600;
}
.quantity-control {
    display: flex;
    align-items: center;
}

.quantity-control .el-button {
    margin: 0 5px;
}
.demo-image__error .image-slot {
    font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
    font-size: 30px;
}
.demo-image__error .el-image {
    width: 100%;
    height: 200px;
}
</style>
